// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const subscribe = db.collection('subscribe')

  let hisSubscribe = []
  await subscribe.where({
    openid: wxContext.OPENID,
  }).get().then(res => {
    console.log('get', res)
    hisSubscribe = res.data
  })

  if (hisSubscribe.length > 0) {
      return {
        openid: wxContext.OPENID,
        msg: "已有订阅"
      }
  }

  let flag = false
  await subscribe.add({
    data: {
      username: event.username,
      passwd: event.passwd,
      openid: wxContext.OPENID,
      setTIme: `${Date.now()}`
    }
  }).then(res => {
    flag = true
  })


  return {
    event,
    openid: wxContext.OPENID,
    context: context,
    flag: flag
    // appid: wxContext.APPID,
    // unionid: wxContext.UNIONID,
  }
}